using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using System.Threading;

namespace SpoonCore.Simulation
{
	class SimulationManager
	{
		private const int Interval = 10;
		private const int CheckWait = 0;
		private System.Timers.Timer _checkTimer = new System.Timers.Timer(Interval * 1000);
		private ISimulation _runningSimulation;
		private Queue<ISimulation> _simQueue = new Queue<ISimulation>();

		public SimulationManager()
		{
			_checkTimer.Elapsed += new ElapsedEventHandler(CheckTimerElapsed);
			_checkTimer.Start();

			Init();
			Start();
		}

		private void Start()
		{
			while (_simQueue.Count > 0)
			{
				ISimulation item = _simQueue.Dequeue();
				Console.WriteLine("Start: " + item);
				_runningSimulation = item;
				item.Run();
			}
		}

		private void CheckTimerElapsed(object sender, ElapsedEventArgs e)
		{
			if (_runningSimulation != null)
			{
				Console.WriteLine("Pause");
				_runningSimulation.Pause();
				Thread.Sleep(CheckWait * 1000);

				Report(_runningSimulation);

				Console.WriteLine("Resume");
				_runningSimulation.Resume();
			}
		}

		private void Report(ISimulation simulation)
		{
			List<SpoonClient> clients = simulation.Clients;

			Console.WriteLine();
			Console.WriteLine("Report (" + DateTime.Now + ")");
			Console.WriteLine("-----------------------------------");

			bool status = true;
			foreach (SpoonClient client in clients)
			{
				if (!client.Check(clients)) status = false;
			}
			Console.Write("Total: ");
			if (status) Console.ForegroundColor = ConsoleColor.Green;
			else Console.ForegroundColor = ConsoleColor.Red;
			Console.WriteLine(status);
			Console.ForegroundColor = ConsoleColor.Gray;

			Console.WriteLine();
		}

		public void AddSimulation(ISimulation simulation)
		{
			_simQueue.Enqueue(simulation);
		}

		private void Init()
		{
			AddSimulation(new RealSimulation());
		}
	}
}
